﻿using NCP.Core;
using NCP.Core.DataUtil;
using NCP.Core.IoC;
using NCP.Model;
using NCP.Util;
using SqlSugar;
using System;
using System.Collections.Generic;

namespace NCP.Service
{
    public class SysOperLogService : IService
    {
        private SqlSugarClient _client;
        public SysOperLogService()
        {
            _client = DbHelper.GetSqlSugarClient();
        }
        public static void WriteSysOperLog(string eventType, string eventCon, string oldCon, string newCon, string memo = null, string operCode = null, string operName = null, DateTime? operDate = null)
        {
            SysOperLog log = new SysOperLog()
            {
                EventType = eventType,
                EventCon = eventCon,
                OldCon = oldCon,
                NewCon = newCon,
                Memo = memo,
                OperCode = operCode,
                OperName = operName,
                OperDate = operDate ?? DateTime.MinValue
            };
            WriteSysOperLog(log);
        }
        public static void WriteSysOperLog(SysOperLog log)
        {
            if (string.IsNullOrEmpty(log.OperCode))
            {
                Member oper = MemberUtil.GetCurrentMember();
                log.OperCode = oper?.Code;
                log.OperName = oper?.Name;
            }
            if (string.IsNullOrEmpty(log.IP))
            {
                log.IP = PublicUtil.GetUserHostIP();
            }
            if (log.OperDate == DateTime.MinValue)
            {
                log.OperDate = DateTime.Now;
            }

            SqlSugarClient client = DbHelper.GetSqlSugarClient();
            try
            {
                client.Insertable(log).ExecuteCommand();
            }
            catch
            {
                //插入失败则插入到本地文件
                try
                {
                    log.Memo += ("|" + Guid.NewGuid().ToString("N"));

                    log4net.ILog logger = log4net.LogManager.GetLogger(typeof(SysOperLogService));
                    logger.Info($"Memo:{log.Memo}\r\n事件类型:{log.EventType}\r\n事件内容:{log.EventCon}\r\nIP地址:{log.IP}\r\n修改前内容:{log.OldCon}\r\n修改后内容:{log.NewCon}\r\n");
                }
                catch { }
                //清除内容再插入一次
                try
                {
                    log.OldCon = null;
                    log.NewCon = null;
                    client.Insertable(log).ExecuteCommand();
                }
                catch { }
            }
        }
    }
}
